﻿using MatrixWebApiCore.Common;
using MatrixWebApiCore.Common.Data;
using MatrixWebApiCore.Dao;
using MatrixWebApiCore.Filter;
using MatrixWebApiCore.HttpRequest;
using MatrixWebApiCore.IDao;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Xml;

namespace MatrixWebApiCore
{
    public class Startup
    {

        public IConfiguration Configuration { get; }
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

//#if DEBUG
//   ModelXmlAddApiXml();
//#endif
        }

        /// <summary>
        /// 为swagger生成实体类xml注释
        /// </summary>
        private void ModelXmlAddApiXml()
        {
            MessageHelper.LogInfo("开始生成xml注释...");
            XmlDocument xmlDocument = new XmlDocument();
            string baseDirePath = AppDomain.CurrentDomain.BaseDirectory;
            //MessageHelper.LogInfo("Application_Start，baseDirePath=" + baseDirePath);
            //读取c#生成的xml注释
            xmlDocument.Load(baseDirePath + @"/MatrixWebApiCore.Entity.xml");
            var membersNode = xmlDocument.GetElementsByTagName("members")[0]; //Model层Members节点
            xmlDocument.Load(baseDirePath + @"/MatrixWebApiCore.xml");
            var currentMembersNode = xmlDocument.GetElementsByTagName("members")[0];  //API层Members节点        
            Parallel.For(0, membersNode.ChildNodes.Count, index =>
             {
                 var memberNode = membersNode.ChildNodes[index];
                 currentMembersNode.AppendChild(memberNode.Clone());
             });
            xmlDocument.Save(baseDirePath + @"/MatrixWebApiCore.xml");
            MessageHelper.LogInfo("生成了xml注释");
        }
 
        //IServiceProvider
        public void ConfigureServices(IServiceCollection services)
        {
            string sqlConnection = SysCoinfgData.SqlServerConnetionString;
            //var sqlConnection = Configuration["connectionStrings:DefaultConnection"];
            services.AddDbContext<DataContext>(option => option.UseSqlServer(sqlConnection));
             
            services.AddScoped<IGroupChartsRepository, GroupChartsRepository>();
            services.AddScoped<ICombinationGroupChartsRepository, CombinationGroupChartsRepository>();
            services.AddScoped<ILogRepository, LogRepository>();
          
            //services.AddSingleton<CombinationWebClientData>();

            services.BuildServiceProvider();          
          
            //支持跨域
            services.AddCors();

            //swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
                {
                    Version = "v1",
                    Title = "基金分析报告管理接口文档",
                    Description = "RESTful API",
                    TermsOfService = "None",
                });
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath = Path.Combine(basePath, "MatrixWebApiCore.xml");
                c.IncludeXmlComments(xmlPath);
                c.OperationFilter<HeaderTokenFilter>(); // 添加httpHeader参数
            });

            //注册内存缓存
            services.AddMemoryCache();
            //services.AddResponseCaching();
            services.AddMvcCore(options =>
            {
                //全局异常过滤器
                options.Filters.Add<ExceptionFilter>();
                //options.CacheProfiles.Add("test1", new CacheProfile());
            })
            //services.AddMvc()
            .AddJsonFormatters()//配置返回json格式数据，不然会报错
            .AddApiExplorer()
            //全局配置Json序列化处理
            .AddJsonOptions(options =>
            {
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //不使用驼峰样式的key
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                //设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });
             
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseCors(c =>
            {
                c.AllowAnyOrigin();
                c.AllowAnyHeader();
                c.AllowAnyMethod();
                c.AllowCredentials();
            });

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs");
            });

            app.UseStaticFiles();
            //app.UseMvc();
            app.UseMvc(routes =>
            {
                routes.MapRoute("default", "api/{controller}/{action}/{id?}");
            });

        }
    }
}
